import { NextFunction, Request, Response } from 'express';
import { getErr } from './getSendResult';
import { pathToRegexp } from 'path-to-regexp';
import jwt from './jwt';
interface Api {
  method: string,
  path: string
}
//不需要token的请求
const dontNeedTokenApi: Api[] = [
  { method: 'GET', path: '/api/login' },
  // { method: 'GET', path: '/api/user/:id' },
  // { method: 'POST', path: '/api/user' },
]
export default (req: Request, res: Response, next: NextFunction) => {
  const apis = dontNeedTokenApi.filter(api => {
    const reg = pathToRegexp(api.path);
    return api.method === req.method && reg.test(req.path);
  })
  if (apis.length > 0) {
    console.log('不需要token');
    next()
    return;
  }
  const result = jwt.verify(req);
  if (result) {//认证通过
    req.userId = result;
    next();
  } else {//认证失败
    handleNoToken(req, res)
  }
}
function handleNoToken(req: Request, res: Response): void {
  res
    .status(403)
    .send(getErr('you dont have any token to access the api', 403))
}